<template>
  <el-dialog
    :title="props.operType === 'add' ? '新增配菜' : '编辑配菜'"
    v-model="visible"
    width="55%"
    append-to-body
  >
    <el-form :model="form" :rules="rules" ref="goodRef" label-width="120px">
      <div v-if="props.operType === 'add'">
        <el-row>
          <el-col :span="8">
            <el-form-item label="城市标签" prop="cityName">
              <el-select @change="getSortListData" v-model="form.cityName" placeholder="请选择">
                <el-option
                  v-for="item in cityNameOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配菜名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入配菜名称" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配菜分类" prop="goodsTypeId">
              <el-select
                v-model="form.goodsTypeId"
                @change="getGoodsTypeName"
                class="m-2"
                placeholder="请选择配菜分类"
              >
                <el-option
                  v-for="item in SortOptions"
                  :key="item.goodsTypeId"
                  :label="item.goodsTypeName"
                  :value="item.goodsTypeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplier">
              <el-input
                v-model="form.supplier"
                placeholder="请输入供应商"
                maxlength="50"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成本价(元)" prop="costPrice">
              <el-input-number
                v-model="form.costPrice"
                :min="0"
                :max="9999"
                :precision="1"
                placeholder="请输入成本价"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原价(元)" prop="salePrice">
              <el-input-number
                v-model="form.salePrice"
                :min="0"
                :max="9999"
                :precision="1"
                placeholder="请输入原价"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保质期(天)" prop="expireDay">
              <el-input-number
                v-model="form.expireDay"
                :min="0"
                :max="365"
                placeholder="请输入保质期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="加热时间(秒)" prop="heatTime">
              <el-input-number
                v-model="form.heatTime"
                :min="0"
                :max="300"
                placeholder="请输入加热时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图" prop="frontImgId">
              <ImageUploadByType
                v-model="form.frontImgId"
                :limit="1"
                :fileSize="10"
                modelType="goods"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="配菜描述" prop="goodsDesc">
              <el-input
                v-model="form.goodsDesc"
                type="textarea"
                placeholder="请输入"
                maxlength="300"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div v-else>
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>配菜信息</span>
            </div>
          </template>
          <div>
            <el-row>
              <el-col :span="8">
                <el-form-item label="城市标签" prop="cityName">
                  <el-select :disabled="editDisabled" v-model="form.cityName" placeholder="请选择">
                    <el-option
                      v-for="item in cityNameOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="配菜编码" prop="goodsId">
                  <el-input v-model="form.goodsId" disabled placeholder="请输入配菜编码" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="配菜名称" prop="goodsName">
                  <el-input v-model="form.goodsName" placeholder="请输入配菜名称" maxlength="50" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="配菜分类" prop="goodsTypeId">
                  <el-select v-model="form.goodsTypeId" clearable class="m-2" placeholder="请选择">
                    <el-option
                      v-for="item in SortOptions"
                      :key="item.goodsTypeId"
                      :label="item.goodsTypeName"
                      :value="item.goodsTypeId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="保质期" prop="expireDay">
                  <el-input v-model="form.expireDay" placeholder="请输入">
                    <template #append>天</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="原价" prop="salePrice">
                  <el-input v-model="form.salePrice" placeholder="请输入">
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="成本价格" prop="costPrice">
                  <el-input v-model="form.costPrice" placeholder="请输入">
                    <template #append>￥</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="配菜描述" prop="goodsDesc">
                  <el-input
                    v-model="form.goodsDesc"
                    type="textarea"
                    placeholder="请输入"
                    maxlength="300"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>配菜详情</span>
            </div>
          </template>
          <div>
            <el-row>
              <el-col :span="12">
                <el-form-item label="口味" prop="taste">
                  <el-select v-model="form.taste" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="dict in goods_taste"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="重量" prop="weight">
                  <el-input v-model="form.weight" placeholder="请输入">
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="热量" prop="calorie">
                  <el-input v-model="form.calorie" placeholder="请输入">
                    <template #append>kal</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="配料" prop="dosing">
                  <el-input v-model="form.dosing" placeholder="请输入" maxlength="200"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" class="bffcol">
                <span class="yyjz">
                  <!-- <span style="color: var(--el-color-danger)">*</span>  -->
                  营养价值</span
                >
                <el-form-item label="" prop="nutritive1">
                  <el-input v-model="form.nutritive1" class="item-input">
                    <template #prepend>脂肪</template>
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="" prop="nutritive2">
                  <el-input v-model="form.nutritive2" class="item-input">
                    <template #prepend>钠</template>
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="" prop="nutritive3">
                  <el-input v-model="form.nutritive3" class="item-input">
                    <template #prepend>碳水化合物</template>
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="" prop="nutritive4">
                  <el-input v-model="form.nutritive4" class="item-input">
                    <template #prepend>膳食纤维</template>
                    <template #append>g</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" class="bffcol">
                <span class="yyjz">
                  <!-- <span style="color: var(--el-color-danger)">*</span>  -->
                  制作步骤</span
                >
                <el-form-item label="" prop="heatTime">
                  <el-input v-model="form.heatTime" class="item-input">
                    <template #prepend>加热时长</template>
                    <template #append>s</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="" prop="temperature">
                  <el-input v-model="form.temperature" class="item-input">
                    <template #prepend>温度</template>
                    <template #append>℃</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>配菜详情图片</span>
            </div>
          </template>
          <div>
            <el-row v-for="(imgItem, imgIndex) in form.goodsDetailImgVoList" :key="imgIndex">
              <el-col :span="24">
                <el-form-item
                  v-if="imgItem.resourceType === 1"
                  :label="imgItem.imgType === 1 ? '封面图' : '详情图'"
                  :prop="imgItem.imgType === 1 ? 'img1' : 'img2'"
                >
                  <ImageUploadByType
                    v-model="imgItem.info"
                    :limit="imgItem.imgType === 1 ? 1 : 5"
                    :fileSize="30"
                    modelType="goods"
                  />
                </el-form-item>
                <el-form-item v-if="imgItem.resourceType === 2" label="视频" prop="video">
                  <VideoUpload v-model="imgItem.info" uploadType="2" :limit="1" modelType="goods" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loadingSubmit">{{
          props.operType === 'add' ? '新增' : '更新'
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { defineProps } from 'vue'
import { addGoods, getGoodsDetail, updateGoods } from '@/api/meal/goods'
import useGlobalStore from '@/store/modules/global'
import { getSortList } from '@/api/meal/goodsType'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const props = defineProps({
  operType: {
    type: String,
    default: 'add'
  }
})

const { proxy } = getCurrentInstance()
const { goods_taste } = proxy.useDict('goods_taste')
const goodRef = ref()
const editDisabled = computed(() => props.operType === 'edit')
const visible = ref(false)
const loadingSubmit = ref(false)
const SortOptions = ref([])
const form = ref({
  goodsName: null,
  goodsDesc: null,
  goodsTypeId: null,
  goodsTypeName: null,
  salePrice: null,
  costPrice: null,
  heatTime: null,
  supplier: null,
  frontImgId: null,
  expireDay: null,
  goodsNutritiveVoList: null,
  cityName: cityNameOptions.value[0]
})

const goodsNutritiveIds = ref({
  nutritive1Id: null,
  nutritive2Id: null,
  nutritive3Id: null,
  nutritive4Id: null
})
const currentId = ref(null)
const emit = defineEmits(['updateList'])

function getSortListData() {
  getSortList({ pageNum: 1, pageSize: 9999, cityName: form.value.cityName }).then((res) => {
    SortOptions.value = res.rows
  })
}

const checMaxNumber = (rule, value, callback) => {
  let maxVal = rule.maxVal || 9999
  const pattern = /^\d+$/
  if (!pattern.test(value)) {
    callback(new Error('请输入数字'))
  } else if (value > maxVal) {
    callback(new Error(`输入不能超过${maxVal}`))
  } else {
    callback()
  }
}
const checkVideo = (rule, value, callback) => {
  let video =
    form.value.goodsDetailImgVoList.filter(
      (item) => item.resourceType === 2 && item.info && item.info.length > 0
    ) || []
  if (video.length == 0) {
    // callback(new Error('视频不能为空'))
    callback()
  } else {
    callback()
  }
}
const checkImg1 = (rule, value, callback) => {
  let img1 =
    form.value.goodsDetailImgVoList.filter(
      (item) => item.imgType === 1 && item.info && item.info.length > 0
    ) || []
  if (img1.length == 0) {
    callback(new Error('封面图不能为空'))
  } else {
    callback()
  }
}
const checkImg2 = (rule, value, callback) => {
  let img2 =
    form.value.goodsDetailImgVoList.filter(
      (item) => item.imgType === 2 && item.info && item.info.length > 0
    ) || []
  if (img2.length == 0) {
    // callback(new Error('详情图不能为空'))
    callback()
  } else {
    callback()
  }
}

const rules = {
  cityName: [{ required: true, message: '城市不能为空', trigger: 'change' }],
  goodsName: [{ required: true, message: '配菜名称不能为空', trigger: 'blur' }],
  goodsTypeId: [{ required: true, message: '配菜分类不能为空', trigger: 'change' }],
  salePrice: [{ required: true, message: '原价不能为空', trigger: 'blur' }],
  costPrice: [{ required: true, message: '成本价格不能为空', trigger: 'blur' }],
  supplier: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
  expireDay: [
    { required: true, message: '保质期不能为空', trigger: 'blur' },
    { validator: checMaxNumber, trigger: 'blur', maxVal: 365 }
  ],
  frontImgId: [{ required: true, message: '封面图不能为空', trigger: 'blur' }],
  goodsDesc: [{ required: true, message: '配菜描述不能为空', trigger: 'blur' }],
  //edit
  // taste: [{ required: true, message: '口味不能为空', trigger: 'blur' }],
  weight: [
    // { required: true, message: '重量不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  calorie: [
    // { required: true, message: '热量不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  // dosing: [{ required: true, message: '配料不能为空', trigger: 'blur' }],
  heatTime: [
    // { required: true, message: '加热时间不能为空', trigger: 'blur' },
    { validator: checMaxNumber, trigger: 'blur', maxVal: 300 }
  ],
  // temperature: [{ required: true, message: '温度不能为空', trigger: 'blur' }],
  nutritive1: [
    // { required: true, message: '脂肪不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  nutritive2: [
    // { required: true, message: '钠不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  nutritive3: [
    // { required: true, message: '碳水化合物不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  nutritive4: [
    // { required: true, message: '膳食纤维不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  img1: [{ required: true, validator: checkImg1, trigger: 'change' }],
  img2: [{ validator: checkImg2, trigger: 'change' }],
  video: [{ validator: checkVideo, trigger: 'change' }]
}

function submitForm() {
  proxy.$refs['goodRef'].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true
      if (props.operType === 'add') {
        let params = { ...form.value, frontImgId: form.value.frontImgId[0].resourceId }
        addGoods(params).then(
          (res) => {
            proxy.$modal.msgSuccess('新增成功')
            emit('updateList')
            visible.value = false
          },
          (error) => {
            loadingSubmit.value = false
          }
        )
      } else {
        ElMessageBox.confirm('确认要修改这行数据吗?', '系统提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          center: false
        })
          .then(() => {
            const flatArray = form.value.goodsDetailImgVoList.flatMap((obj) => {
              if (obj.info) {
                return obj.info.map((infoObj) => {
                  return {
                    id: infoObj.id,
                    goodsId: currentId.value,
                    imgType: obj.imgType,
                    resourceType: obj.resourceType,
                    resourceId: infoObj.resourceId,
                    resourceUrl: infoObj.resourceUrl ? infoObj.resourceUrl : infoObj.url
                  }
                })
              }
            })
            const result = { goodsDetailImgVoList: flatArray }
            let nutritiveList = [
              {
                id: goodsNutritiveIds.value.nutritive1Id
                  ? goodsNutritiveIds.value.nutritive1Id
                  : undefined,
                goodsId: currentId.value,
                nutritive: '脂肪',
                value: form.value.nutritive1
              },
              {
                id: goodsNutritiveIds.value.nutritive2Id
                  ? goodsNutritiveIds.value.nutritive2Id
                  : undefined,
                goodsId: currentId.value,
                nutritive: '钠',
                value: form.value.nutritive2
              },
              {
                id: goodsNutritiveIds.value.nutritive3Id
                  ? goodsNutritiveIds.value.nutritive3Id
                  : undefined,
                goodsId: currentId.value,
                nutritive: '碳水化合物',
                value: form.value.nutritive3
              },
              {
                id: goodsNutritiveIds.value.nutritive4Id
                  ? goodsNutritiveIds.value.nutritive4Id
                  : undefined,
                goodsId: currentId.value,
                nutritive: '膳食纤维',
                value: form.value.nutritive4
              }
            ]
            let params = { ...form.value, ...result, goodsNutritiveVoList: nutritiveList }
            updateGoods(params)
              .then((res) => {
                proxy.$modal.msgSuccess('更新成功')
                emit('updateList')
                visible.value = false
              })
              .catch((err) => {
                loadingSubmit.value = false
              })
          })
          .catch(() => {
            loadingSubmit.value = false
          })
      }
    }
  })
}

function getGoodsTypeName(goodsTypeId) {
  const selectedType = SortOptions.value.find((option) => option.goodsTypeId === goodsTypeId)
  form.value.goodsTypeName = selectedType ? selectedType.goodsTypeName : null
}

async function show(type, id) {
  reset()
  visible.value = true
  if (type === 'edit') {
    await getDetailData(id)
    getSortListData()
    currentId.value = id
    return
  } else if (type === 'add') {
    form.value.cityName = id
    getSortListData()
  }
}
async function getDetailData(goodsId) {
  await getGoodsDetail(goodsId).then((res) => {
    form.value = res?.data
    if (res.data.goodsNutritiveVoList) {
      const nutritive1Arr = res.data.goodsNutritiveVoList.find((ele) => ele.nutritive === '脂肪')
      form.value.nutritive1 = nutritive1Arr?.value
      goodsNutritiveIds.value.nutritive1Id = nutritive1Arr?.id
      const nutritive2Arr = res.data.goodsNutritiveVoList.find((ele) => ele.nutritive === '钠')
      form.value.nutritive2 = nutritive2Arr?.value
      goodsNutritiveIds.value.nutritive2Id = nutritive2Arr?.id
      const nutritive3Arr = res.data.goodsNutritiveVoList.find(
        (ele) => ele.nutritive === '碳水化合物'
      )
      form.value.nutritive3 = nutritive3Arr?.value
      goodsNutritiveIds.value.nutritive3Id = nutritive3Arr?.id
      const nutritive4Arr = res.data.goodsNutritiveVoList.find(
        (ele) => ele.nutritive === '膳食纤维'
      )
      form.value.nutritive4 = nutritive4Arr?.value
      goodsNutritiveIds.value.nutritive4Id = nutritive4Arr?.id
    }
    if (!res.data.goodsDetailImgVoList) {
      form.value.goodsDetailImgVoList = [
        {
          goodsId: goodsId,
          resourceId: null,
          imgType: 1,
          resourceType: 1,
          resourceUrl: null
        },
        {
          goodsId: goodsId,
          resourceId: null,
          imgType: 2,
          resourceType: 1,
          resourceUrl: null
        },
        {
          goodsId: goodsId,
          resourceId: null,
          imgType: null,
          resourceType: 2,
          resourceUrl: null
        }
      ]
    } else {
      // console.log("res.data.goodsDetailImgVoList===============",res.data.goodsDetailImgVoList)
      // resourceType 2 视频  resourceType 1 imgType 1封面  resourceType 1 imgType 2详情图
      res.data.goodsDetailImgVoList.forEach((element) => {
        element.url = element.resourceUrl
      })
      let arr1 = res.data.goodsDetailImgVoList.filter((item) => item.resourceType === 2)
      let arr2 = res.data.goodsDetailImgVoList.filter(
        (item) => item.resourceType === 1 && item.imgType === 1
      )
      let arr3 = res.data.goodsDetailImgVoList.filter(
        (item) => item.resourceType === 1 && item.imgType === 2
      )
      let obj1 = {
        resourceType: 2,
        imgType: null,
        info: arr1
      }
      let obj2 = {
        resourceType: 1,
        imgType: 1,
        info: arr2
      }
      let obj3 = {
        resourceType: 1,
        imgType: 2,
        info: arr3
      }
      form.value.goodsDetailImgVoList = [obj2, obj3, obj1]
    }
  })
}

function reset() {
  form.value = {
    goodsName: null,
    goodsDesc: null,
    goodsTypeId: null,
    goodsTypeName: null,
    salePrice: null,
    costPrice: null,
    heatTime: null,
    supplier: null,
    frontImgId: null,
    expireDay: null,
    temperature: null,
    vipPrive: null,
    miniPrice: null,
    dosing: null,
    img1: null,
    img2: null,
    video: null
  }
  goodsNutritiveIds.value = {
    nutritive1Id: null,
    nutritive2Id: null,
    nutritive3Id: null,
    nutritive4Id: null
  }
  if (goodRef.value) {
    goodRef.value.resetFields()
  }
  loadingSubmit.value = false
}

defineExpose({
  show
})
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-input {
  margin-bottom: 5px;
}
:deep(.el-input-group__prepend) {
  background-color: #f5f7fa00 !important;
}
:deep(.el-card__body) {
  padding: 15px 20px 10px 20px !important;
}

.bffcol {
  position: relative;
  .yyjz {
    position: absolute;
    top: 4px;
    left: 45px;
    font-size: var(--el-form-label-font-size);
    color: var(--el-text-color-regular);
    height: 32px;
    line-height: 32px;
    font-weight: 700;
  }
}
</style>
